var END_POINT = 'https://oss-cn-beijing.aliyuncs.com'; //阿里云OSS服务在各个区域的地址
var ACCESS_KEY_ID = 'LTAI4FiY1zoVAeFKspnJuLeH'; //从阿里云获取的accessKeyId
var ACCESS_KEY_SECRET = '9K889H4GdLYclI78WFfGp0CkRacAUZ'; //从阿里云获取的accessKeySecret
var BASE_URL = 'https://langwen.oss-cn-beijing.aliyuncs.com'; //文件对外的域名，去掉了前面的http,因为在fnCacheImage()函数中会添加：http://paekdusan.oss-cn-beijing.aliyuncs.com
var BUCKET_NAME = "langwen"; //Bucket名称
var FOLDER = 'app/'; //Folder名称
// 选择图片，以及上传华为云
var UIAlbumBrowser;
//拍照或者选择照片
var _newImgType = "";
// 上传完成后的监听事件
var _callbackEvent = '';

/**
 * 阿里云OSS初始化：支持明文模式和自签名模式 。移动终端是一个不受信任的环境，如果把AccessKeyId和AccessKeySecret
 * 直接保存在终端本地用来加签请求，存在极高的风险。明文模式鉴权必须设置accessKeyId和accessKeySecret，此方式建议
 * 只在测试时使用。正式环境请使用自签名模式，此模式serverUrl为必须。
 * 目前使用的是明文模式。
 */
var aliyunOSS;

function fnInitAliYunOss() {
    aliyunOSS = api.require('aliyunOSS');
    aliyunOSS.initOSSClient({
        endpoint: END_POINT,
        accessKeyId: ACCESS_KEY_ID,
        accessKeySecret: ACCESS_KEY_SECRET,
    }, function(ret, err) {
        if (ret) {
            console.log(JSON.stringify(ret));
        }
    });
}

function fnUploadImg(max, callbackEvent) {
    _callbackEvent = callbackEvent;
    var resultList = api.hasPermission({
        list: ['camera', 'photos']
    });
    if (!resultList[0]['granted']||!resultList[1]['granted']) {
        api.requestPermission({
            list: ['camera', 'photos']
        }, function(ret) {
            if (ret && ret.list) {
                console.log(JSON.stringify(ret))
                if (!ret.list[0]['granted'] || !ret.list[1]['granted']) {
                    fnToast('您没有允许相关权限，请允许后继续');
                }
            }
        })
    }
    api.actionSheet({
        title: '',
        cancelTitle: '取消',
        destructiveTitle: '',
        buttons: ['拍照', '从相册获取']
    }, function(ret, err) {
        if (ret) {
            fnOpenSelPhoto(ret.buttonIndex, max)
        }
    });
}

function fnOpenPhoto(newImgType, max) {
    var resultList = api.hasPermission({
        list: ['camera', 'photos']
    });
    if (!resultList[0]['granted']||!resultList[1]['granted']) {
        api.requestPermission({
            list: ['camera', 'photos']
        }, function(ret) {
            if (ret && ret.list) {
                console.log(JSON.stringify(ret))
                if (!ret.list[0]['granted'] || !ret.list[1]['granted']) {
                    fnToast('您没有允许相关权限，请允许后继续');
                }
            }
        })
    }
    _newImgType = newImgType;
    api.actionSheet({
        title: '',
        cancelTitle: '取消',
        destructiveTitle: '',
        buttons: ['拍照', '从相册获取']
    }, function(ret, err) {
        if (ret) {
            fnOpenSelPhoto(ret.buttonIndex, max)
        }
    });
}

function fnOpenSelPhoto(type, max) {
    if (type == '1') {
        var resultList = api.hasPermission({
            list: ['camera']
        });
        if (!resultList[0]['granted']) {
            api.requestPermission({
                list: ['camera']
            }, function(ret) {
                if (ret && ret.list) {
                    if (!ret.list[0]['granted']) {
                        fnToast('相机权限未开启，请允许后继续');
                    } else {
                        fnOpenCamera();
                    }
                }
            })
        }else {
            fnOpenCamera();
        }
    } else if (type == '2') {
        UIAlbumBrowser = api.require('UIAlbumBrowser');
        if (api.systemType == 'ios') {
            UIAlbumBrowser.requestAlbumPermissions({}, function(ret, err) {
                if (ret.isAccessPermissions) {
                    fnOpenSelectPhoto(max);
                } else {
                    fnToast("相册权限未开启")
                }
            });
        } else {
            fnOpenSelectPhoto(max);
        }
    }
}

function fnOpenCamera() {
    api.getPicture({
        sourceType: 'camera',
        encodingType: 'jpg',
        mediaValue: 'pic',
        destinationType: 'url',
        allowEdit: true,
        quality: 100,
        // targetWidth: 100,
        // targetHeight: 100,
        saveToPhotoAlbum: false
    }, function(ret, err) {
        if (ret && ret.data != '') {
            var _imgUrl = [];
            imgURLItem = {
                "path": ret.data
            };
            _imgUrl.push(imgURLItem);
            if(_callbackEvent.length > 0) {
                var callback = function(url) {
                    api.sendEvent({
                        name: _callbackEvent,
                        extra: {
                            imgs: [url]
                        }
                    });
                    _callbackEvent = '';
                };
                fnUploadObsFile(ret.data, callback);
            }else {
                api.sendEvent({
                    name: 'imgURL',
                    extra: {
                        type: _newImgType,
                        imgURL: _imgUrl
                    }
                });
            }
        }
    });
}



function fnOpenSelectPhoto(max) {
    UIAlbumBrowser = api.require('UIAlbumBrowser');
    UIAlbumBrowser.open({
        max: max,
        styles: {
            bg: '#fff',
            mark: {
                icon: '',
                position: 'bottom_left',
                size: 20
            },
            nav: {
                bg: 'rgba(0,0,0,0.6)',
                titleColor: '#fff',
                titleSize: 18,
                cancelColor: '#fff',
                cancelSize: 16,
                finishColor: '#fff',
                finishSize: 16
            }
        },
        rotation: true
    }, function(ret) {
        if (ret) {
            if (ret.eventType == 'confirm') {
                if (ret.list.length > 0) {
                    fnRecursionPic(ret.list, '0')
                }
            }
        }
    });
}
var _submitImg = [];

function fnRecursionPic(imgArr, key) {
    if (key == '0') {
        _submitImg = [];
    }
    UIAlbumBrowser.transPath({
        path: imgArr[key].path
    }, function(ret, err) {
        if (ret) {
            key = parseInt(key) + 1;
            var _imgItem = {
                path: ret.path
            }
            _submitImg.push(_imgItem)
            if (key == imgArr.length) {
                if(_callbackEvent.length > 0) {
                    var _index = 0, upResult = [];
                    function upload() {
                        var callback = function(url) {
                            upResult.push(url);
                            if(upResult.length == _submitImg.length) {
                                api.sendEvent({
                                    name: _callbackEvent,
                                    extra: {
                                        imgs: upResult
                                    }
                                })
                                _callbackEvent = '';
                            }else {
                                _index ++;
                                upload();
                            }
                        };
                        fnUploadObsFile(_submitImg[_index].path, callback);
                    };
                    upload();
                }else {
                    api.sendEvent({
                        name: 'imgURL',
                        extra: {
                            type: _newImgType,
                            imgURL: _submitImg
                        }
                    });
                }
            } else {
                fnRecursionPic(imgArr, key)
            }
        }
    });
}

function fnUploadObsFile(fileurl, pCallBack) {
    if (fileurl.indexOf('http') >= 0) {
        pCallBack(fileurl);
    } else {
        var timestamp = new Date().getTime() + Math.ceil(Math.random() * 1000);
        var s = fileurl;
        console.log(fileurl)
        var photoSrc = s.split("/");
        var photoName = FOLDER + timestamp + photoSrc[photoSrc.length - 1];
        console.log("上传文件名为：" + photoName);
        aliyunOSS.upload({
            file: fileurl,
            bucketName: BUCKET_NAME,
            objectKey: photoName,
            uploadType: 1,
        }, function(ret, err) {
            console.log(JSON.stringify(ret));
                console.log(JSON.stringify(err));
            if (ret) {
                if (ret.oper == "complete") {
                    var pImg = BASE_URL + '/' + photoName;
                    pCallBack(pImg);
                }
            } else {
                fnUploadObsFile(fileurl,pCallBack)
            }
        });
    }
}
